﻿package com.dLibs
{
	import com.dLibs.events.Events;
	
	import flash.display.Bitmap;
	import flash.display.Loader;
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.events.ProgressEvent;
	import flash.net.URLRequest;
	
	public class loadit extends MovieClip
	{
		private var loaditLoader:Loader;
		private var loaditRequest:URLRequest;
		private var _targetIt:String;
		private var _smooth:Boolean;
		
		public 	var loaditPercent:uint;
		
		public function loadit(targetIt:String, smooth:Boolean = false):void
		{
			_targetIt = targetIt;
			_smooth = smooth;
			
			super.addEventListener(Event.ADDED_TO_STAGE, init);
			super.addEventListener(Event.REMOVED_FROM_STAGE, removeClass);
		}
		
		private function init(e:Event):void
		{
			loaditLoader 	= new Loader();
			loaditRequest 	= new URLRequest(_targetIt);
			
			loaditLoader.load(loaditRequest);
			loaditLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, loaditComplete);
			loaditLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, loaditProgress);
			super.addChild(loaditLoader);
		}
		
		private function loaditProgress(p:ProgressEvent):void
		{
			loaditPercent = Math.ceil( ( p.bytesLoaded / p.bytesTotal ) * 100 );
			dispatchEvent(new Events(Events.PROGRESS, { percentLoaded:loaditPercent }));
		}
		
		private function loaditComplete(e:Event):void
		{
			dispatchEvent(new Events(Events.COMPLETE, { loadit : this }));
			if ( _smooth )
			{
				var bmp:Bitmap = e.currentTarget.content;
				bmp.smoothing = true;
			}
		}
		
		private function removeClass(e:Event):void
		{
			loaditLoader.unload();
			loaditLoader.contentLoaderInfo.removeEventListener(Event.COMPLETE, loaditComplete);
			loaditLoader.contentLoaderInfo.removeEventListener(ProgressEvent.PROGRESS, loaditProgress);
		}
	}
}